 // pages/gushi/gushi.js
let api = require('../../api/api.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    count:4,
    searchParam: { page: 1},//搜索参数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(data) {
    console.log(data)
    this.getInfo(true)
  },


  wenzhang: function(e) {
    var id = e.currentTarget.id
    id = encodeURIComponent(id)
    console.log(id)
    wx.navigateTo({
      url: 'wenzhang/wenzhang?id=' + id,
    })
  },

  getInfo:function(isClear){
    var that = this
    that.setSearchParam();
    console.log(that.data.searchParam)
    api.gushi(that.data.searchParam, (res) => {
      console.log(res)
      this.setData({
        gushi: that.setResults(res.data.result.story, isClear),
        count: res.data.result.count
      })
      that.reloadSearchParam(res.data.result);
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function(data) {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  //将页码置0
  clearCurPage: function () {
    var that = this;
    var param = that.data.searchParam;
    param.page = 1;

    that.setData({
      searchParam: param
    });
  },

  //页码翻页
  addCurPage: function () {
    var that = this;
    var param = that.data.searchParam;
    if (param.page) {
      param.page = parseInt(param.page) + 1;
    }
    else {
      param.page = 2;
    }
    console.log(param)
    that.setData({
      searchParam: param
    });
  },
  /**
   * 设置参数
   */
  setSearchParam: function () {
    var that = this;
    var param = this.data.searchParam;
    that.setData({
      searchParam: param
    });
  },
  /**
   * 更新参数
   */
  reloadSearchParam: function (param) {
    var that = this;
    var paramObj = that.data.searchParam;
    if (!paramObj.page) paramObj.page = 1;

    if (paramObj.page <= param.count) {
      console.log(param)
      that.addCurPage();//后台页码从0开始，前台页码从1开始

      that.setData({
        searchParam: paramObj
      });
    }

  },
  setResults(list, isClear) {
    var that = this;
    var oldList = isClear ? [] : that.data.gushi;
    var newList = list;
    console.log(oldList)
    newList.forEach(function (index, element) {
      oldList.push(index);
    });

    return oldList;
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function(r) {
    if(this.data.searchParam.page <= this.data.count){
      this.getInfo()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})